<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('TT.RoomSet.Title') }}</view>
      </HeaderLayout>
    </template>

    <view class="container">
      <PageTitle
        :title="$t('TT.RoomSet.SetTemp.Lable')"
        :temp="curTemp"
        :page-hint="powerStatus ? modeText : ''"
      ></PageTitle>

      <!-- 开关 -->
      <view class="power-box">
        <view class="power-content">
          <view class="power-img flex-center" :class="{ 'not-active': !powerStatus }" @click="setOff">
            <image v-if="powerStatus" :src="'/pages/appliance/static/TurnOn.png'" mode="widthFix"></image>
            <image v-else :src="'/pages/appliance/static/TurnOn.png'" mode="widthFix"></image>
          </view>
          <view class="tip-popup placement-bottom" v-if="!powerStatus">
            <text>{{ $t('TT.RoomSet.PleaseOnOff.Tips.Text') }}</text>
          </view>
        </view>
      </view>

      <!-- 主要内容 -->
      <view class="roomset-box">
        <view class="mask-alayer" v-if="!powerStatus"></view>
        <view class="tab-box" :class="{ poweroffBg: !powerStatus }">
          <view class="tabs-box">
            <view class="tabs" style="width: 100%">
              <view class="tab" :class="{ active: curTab === 0 }" @click="chooseTab(0, 1)">
                <view class="tab-text">{{ $t('TT.RoomSet.Tab.ManualMode.Text') }}</view>
                <view class="tabLine"></view>
              </view>
              <view class="tab" :class="{ active: curTab === 1 }" @click="chooseTab(1, 0)">
                <view class="tab-text">{{ $t('TT.RoomSet.Tab.CommutersMode.Text') }}</view>
                <view class="tabLine"></view>
              </view>
              <view class="tab" :class="{ active: curTab === 2 }" @click="chooseTab(2, 0)">
                <view class="tab-text">{{ $t('TT.RoomSet.Tab.OldYoungMode.Text') }}</view>
                <view class="tabLine"></view>
              </view>
            </view>
          </view>
        </view>
        <!-- 手动设定 -->
        <view class="tab1" :class="{ poweroffBg: !powerStatus }" v-show="curTab === 0">
          <view class="quick-temp bg-color">
            <view class="tem-fav" :class="{ cur: mode === 2 }" @click="chooseManual(2, 20)">{{
              $t('TT.RoomSet.Tab.ManualMode.OnHome.Text')
            }}</view>
            <view
              class="line-division"
              :style="mode === 2 || mode === 3 ? 'background-color: transparent;' : ''"
            ></view>
            <view class="tem-fav" :class="{ cur: mode === 3 }" @click="chooseManual(3, 18)">{{
              $t('TT.RoomSet.Tab.ManualMode..SleepHome.Text')
            }}</view>
            <view
              class="line-division"
              :style="mode === 3 || mode === 4 ? 'background-color: transparent;' : ''"
            ></view>
            <view class="tem-fav" :class="{ cur: mode === 4 }" @click="chooseManual(4, 8)">{{
              $t('TT.RoomSet.Tab.ManualMode.OnlineHome.Text')
            }}</view>
          </view>
          <ChooseTemp
            isUnit
            :data="powerStatus ? degrees : degreesOff"
            :cur-index="curIndex"
            @chooseTemp="chooseTemp"
            @pickState="changePickState"
          />
          <view class="quick-warm-up">
            <view class="warm-up-top-view">
              <text>{{ $t('TT.RoomSet.RapidHeat.Lable') }}</text>
              <view class="display-center" @click="showQuickWarmUpPopView">
                <image class="switch-icon" v-if="rapidHeat" src="@/pages/appliance/static/TT/switch_on.png"></image>
                <image class="switch-icon" v-else src="@/pages/appliance/static/TT/switch_off.png"></image>
              </view>
            </view>
            <view class="warm-up-detail-view" v-if="rapidHeat" @click="showQuickWarmUpPopView">
              <view>{{ curHeatTemp }}℃, {{ curHeatTime }}{{ $t('TT.RoomSet.RapidHeat.Hour.Unit.Text') }}</view>
              <image class="warm-up-right-Icon" :src="'/static/ic_right_arrow.png'"></image>
            </view>
          </view>
        </view>
        <!-- 上班一族 -->
        <view class="tab2" v-show="curTab === 1">
          <view class="quick-temp">
            <view class="quick-temp-left">
              <view class="quick-temp-out-box">
                <view class="quick-temp-box" :class="{ 'active-box': timeTab == 0 }" @click="switchTimeTab(0)">{{
                  $t('TT.RoomSet.Tab.CommutersMode.OneFive.Text')
                }}</view>
                <view class="quick-temp-box" :class="{ 'active-box': timeTab == 1 }" @click="switchTimeTab(1)">{{
                  $t('TT.RoomSet.Tab.CommutersMode.Weekend.Text')
                }}</view>
              </view>
            </view>
            <view class="quick-temp-right"
              >{{ $t('TT.RoomSet.MechineStudy.Lable')
              }}<view @click="showPreheatDesc">
                <image src="@/pages/appliance/static/TT/ic_setting_runningmode.png" class="mode-hint"></image>
              </view>
              <switch color="#108ee9" :checked="preHeat" @change="controlPreheat" />
            </view>
          </view>
        </view>
        <!-- 家有老幼 -->
        <view class="tab3" v-show="curTab === 2">
          <view class="quick-temp">
            <view class="quick-temp-left">
              <view class="quick-temp-box active-box" style="flex: 0.5">{{ $t('TT.RoomSet.EveryDay.Lable') }}</view>
            </view>
            <view class="quick-temp-right"
              >{{ $t('TT.RoomSet.MechineStudy.Lable') }}
              <view @click="showPreheatDesc">
                <image src="@/pages/appliance/static/TT/ic_setting_runningmode.png" class="mode-hint"></image>
              </view>
              <switch color="#108ee9" :checked="preHeat" @change="controlPreheat" />
            </view>
          </view>
        </view>
      </view>
      <!-- canvas -->
      <view class="container1">
        <ec-canvas
          v-if="curTab !== 0"
          id="myChartDomLine"
          canvas-id="mychart-line"
          :echarts="echarts"
          :ec="ecOptions"
        />
      </view>
    </view>

    <template #footer>
      <FooterLayout :size="footerSize" :footer-style="footerStyle">
        <ActionButton :disabled="disabled || !powerStatus" @click="optionConfirm">{{
          $t('TT.RoomSet.Bottom.Button')
        }}</ActionButton>
      </FooterLayout>
    </template>

    <!-- 提示 -->
    <Modal
      v-model:visible="preheatDesc"
      :title="$t('TT.RoomSet.MechineStudy.Dialog.Title')"
      :ok-text="$t('TT.RoomSet.MechineStudy.Dialog.Ok.Button')"
    >
      <view class="tips-text">{{ $t('TT.RoomSet.MechineStudy.Dialog.Content.Text') }}</view>
    </Modal>
    <!-- 房间开关电源提示 -->
    <Modal
      v-model:visible="onOffVisible"
      :title="$t('TT.RoomSet.PowerOff.Dialog.Title')"
      :description="$t('TT.RoomSet.PowerOff.Dialog.Des.Text')"
      :cancel-text="$t('TT.RoomSet.PowerOff.Dialog.Cancel.Text')"
      :ok-text="$t('TT.RoomSet.PowerOff.Dialog.Ok.Text')"
      @ok="onOff"
    />
    <!-- 应用到所有房间提示框 -->
    <Modal
      v-model:visible="applayAllRoomVisible"
      :title="$t('TT.RoomSet.ApplayAllRoom.Dialog.Title')"
      :description="$t('TT.RoomSet.ApplayAllRoom.Dialog.Des.Text')"
      :cancel-text="$t('TT.RoomSet.ApplayAllRoom.Dialog.Cancel.Text')"
      :ok-text="$t('TT.RoomSet.ApplayAllRoom.Dialog.Ok.Text')"
      @cancel="cancelmManual"
      @ok="confirmManual"
    />
    <!-- 快速加热模式 -->
    <Drawer :title="$t('TT.RoomSet.RapidHeat.Dialog.Title')" v-model:show="showRapidHeat" alignment="left">
      <view class="rapid-heat">
        <view class="rapid-heat-desc">
          {{ $t('TT.RoomSet.RapidHeat.Dialog.Introduce.Text') }}
        </view>
        <view class="rapid-heat-box">
          <view class="rapid-heat-title"
            >{{ $t('TT.RoomSet.RapidHeat.Temp.Lable') }}<text class="unit">（℃）</text></view
          >
          <view class="rapid-heat-ul">
            <view
              class="rapid-heat-li lagerLi"
              :class="{ activeView: curHeatTemp == index + 25 }"
              v-for="(item, index) in 6"
              :key="index"
              @click="changHeatTemp(index + 25)"
            >
              {{ 25 + index }}
            </view>
          </view>
        </view>
        <view class="rapid-heat-box">
          <view class="rapid-heat-title"
            >{{ $t('TT.RoomSet.RapidHeat.Time.Lable')
            }}<text class="unit">{{ $t('TT.RoomSet.RapidHeat.Time.Unit.Text') }}</text></view
          >
          <view class="rapid-heat-ul">
            <view
              class="rapid-heat-li lagerLi"
              :class="{ activeView: curHeatTime === Number(item) }"
              v-for="(item, index) in curHeatTimeList"
              :key="index"
              @click="changeRapidHeat(item)"
            >
              {{ item }}
            </view>
          </view>
        </view>
      </view>
      <template #footer>
        <view class="activation-time-btn display-around">
          <view class="time-btn cancel--btn" @click="showRapidHeat = false">{{
            $t('TT.RoomSet.RapidHeat.Cancle.Button')
          }}</view>
          <view class="time-btn save-btn" @click="confirmRapidHeat">{{ $t('TT.RoomSet.RapidHeat.Ok.Button') }}</view>
        </view>
      </template>
    </Drawer>
    <!-- EMS OTA升级弹框 -->
    <OtaUpgradeIRF :show="isMR100IRF" :mcu-status="mcuStatus"></OtaUpgradeIRF>
  </PageLayout>
</template>

<script lang="ts">
export type SettingsSubmitType = {
  settings: { key: string; value: string | number }[]
}
</script>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import FooterLayout from '@/layout/page/footer.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import PageTitle from '../components/pageTitle/pageTitle.vue'
import ChooseTemp from '../components/chooseTemp/chooseTemp.vue'
import Modal from '@/common/modal.vue'
import Drawer from '@/common/drawer.vue'
import OtaUpgradeIRF from '../otaUpgrade/otaUpgradeIRF.vue'

import { footerStyle, footerSize } from '@/layout/appliance/style'
import type { TTController } from '@/controller/TT/definition'
import { actionDebounce, showLoading, useEventReceiver } from '@/utils/mpHelper'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import {
  getTTRoomDetail,
  setTTSetting,
  type TTRoomDetailType,
  getBLTTSetting,
  getBLTTSpecialSetting,
  type BLTTSettingValueType,
} from '@/api/tt'
import {
  getRoomPreheat,
  getTTAutoMode,
  getTTRoomMode,
  getTTRoomTmMode,
  getTTSummerMode,
  setRoomPreheat,
  setTTProgramDay,
  setTTProgramMode,
  setTTRoomMode,
  TT_SETTING_BlState,
  TT_STATUS_MCUSTATUS,
} from '../SmartAssistantTool'
import type { WS } from '@/utils/socket/types'
import { TT_SUMMER_MODE } from '@/constants/Command'
import type { EcCanvasOptions, EcCanvasComponent } from '@/pages/appliance/TT/ec-canvas/ec-canvas'
import { useRoomDayData } from '../chartData/chartData'
import type { Remote } from '@/controller/base/types/remote'
import { useEnvStore } from '@/store/env'
import { getEcharts } from '../useEcharts'
import type { RoomListType } from '../TTHelper'

const echarts = getEcharts()

const headerStyle = {
  backgroundColor: '#fff',
}
const degrees = ref<{ value: number }[]>([])
const degreesOff = ref<{ value: string }[]>([])
for (let i = 5; i <= 35; i += 0.5) {
  degrees.value.push({
    value: i,
  })
  degreesOff.value.push({
    value: '- -',
  })
}
const MODES = new Map([
  [0, '自动'],
  [1, '手动设定'],
  [2, '在家'],
  [3, '睡眠'],
  [4, '离家'],
])
const PACKAGE_ARRAY = [0, 6, 12, 19]

const control = ref<TTController.Control | null>(null)
let roomDayControl: ReturnType<typeof useRoomDayData> | null = null
useEventReceiver('control', (received: TTController.Control) => {
  control.value = received
  listenMessages()
  roomDayControl = useRoomDayData({ tempLineData, dataV })
})
const tempLineData = ref<[number, number][]>([])
const dataV = ref<{ value: number[] }[]>([])

const ecOptions: EcCanvasOptions = {
  lazyLoad: true,
}

const haId = ref('')
const isMR100IRF = computed(() => haId.value.split('-')[1] === 'MR100iRF10720')

const disabled = ref(false)
const roomName = ref('')
const roomIndex = ref(0)
const roomKey = ref('')
const roomId = ref('0')
const curTemp = ref('--')
const setTemp = ref('--')
const powerStatus = ref(true)
const modeText = ref('') //当前模式
const roomList = ref<RoomListType[]>([])
const curTab = ref(0)
const rapidHeat = ref(false)
const mode = ref(0)
const tempMode = ref(0)
const curIndex = ref(0)
const tempIndex = ref(0)
const pickState = ref(false)
const preHeat = ref(false)
const timeTab = ref(0)
const curHeatTemp = ref(25)
const curHeatTime = ref(1)
const curHeatTimeList = ref([1, 2, 3])
const candidateTemp = ref(25)
const candidateTime = ref(1)

const roomConfig = ref('')
const roomState = ref(0)

const summerMode = ref(false)
const manualMode = ref(false)

const showRoomDialog = ref(false)
const preheatDesc = ref(false)

const showRapidHeat = ref(false)

const mcuStatus = ref(0)

onLoad((query: any) => {
  haId.value = query?.haId
  roomName.value = decodeURIComponent(query?.name)
  roomIndex.value = query?.curIndex ? parseInt(query?.curIndex) : 0
  roomList.value = JSON.parse(decodeURIComponent(query?.roomList))
  roomKey.value = roomList.value[roomIndex.value].key
  roomId.value = roomKey.value.replace('Rm', '')
  if (isMR100IRF.value) {
    getTTRoomDetailFun()
  } else {
    let roomDetail = roomList.value[roomIndex.value]
    initInfo(roomDetail.value)
  }
  initChart()
})

onUnload(() => {
  control.value?.remote.removeBatchObserves(observes)
})

/**
 * 加载房间详情数据接口
 */
async function getTTRoomDetailFun() {
  const res = await getTTRoomDetail(haId.value, roomId.value)
  let roomDetail = res.data['room' + roomId.value]
  initInfo(roomDetail)
}
/**
 * 初始化详情数据
 * @param list
 */
function initInfo(list: TTRoomDetailType[]) {
  if (!list || list.length === 0) return
  list.forEach((item, index) => {
    if (item.key === 'Set' || item.key === 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set') {
      let findIndex = degrees.value.findIndex((degrees) => degrees.value === Number(item.value) / 10)
      curIndex.value = findIndex
      tempIndex.value = findIndex
      setTemp.value = degrees.value[findIndex].value + ''
    } else if (item.key === 'Mode') {
      mode.value = Number(item.value)
      tempMode.value = Number(item.value)
      modeText.value = MODES.get(Number(item.value)) || '自动'
      powerStatus.value = !(Number(item.value) === 5)
    } else if (item.key === 'Temp' || item.key == 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Temp') {
      curTemp.value = Number(item.value) / 10 + ''
    } else if (item.key == 'Preheat') {
      preHeat.value = item.value === 1
    } else if (item.key === 'Boost' || item.key == 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost') {
      let formatBoost = parseInt(item.value as string).toString(16)
      let isbool = !(parseInt(item.value as string) === 0)
      rapidHeat.value = isbool
      if (isbool) {
        curHeatTemp.value = 24 + Number(formatBoost.substr(0, 1))
        curHeatTime.value = Number(formatBoost.substr(1, 1))
        candidateTemp.value = 24 + Number(formatBoost.substr(0, 1))
        candidateTime.value = Number(formatBoost.substr(1, 1))
      }
    } else if (item.key === 'TmMode') {
      if (mode.value === 0) {
        curTab.value = Number(item.value) === 20 ? 2 : Number(item.value) === 0 ? 0 : 1
        if (curTab.value !== 0) {
          getRoomDayData(1, Number(item.value))
        }
      }
    } else if (item.key === 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config') {
      roomConfig.value = item.value + ''
      let newMode = getTTRoomMode(item.value + '')
      mode.value = newMode
      tempMode.value = newMode
      modeText.value = MODES.get(newMode) || '自动'
      powerStatus.value = !(newMode === 5)

      if (newMode === 0) {
        let tmMode = getTTRoomTmMode(item.value + '')
        curTab.value = tmMode == 0 ? 2 : 1
        getRoomDayData(1, Number(item.value))
      }
    } else if (item.key === 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State') {
      roomState.value = Number(item.value)
      let newPreHeat = getRoomPreheat(item.value + '')
      preHeat.value = newPreHeat ? true : false
    } else if (item.key === TT_STATUS_MCUSTATUS) {
      mcuStatus.value = item.value as number
    } else if (item.key === TT_SETTING_BlState) {
      if (getTTSummerMode(item.value + '') === 1) {
        summerMode.value = true
      }
      if (getTTAutoMode(item.value + '') === 1) {
        manualMode.value = true
      }
    }
  })
}
/**
 * 切换curtab
 */
function chooseTab(tabIndex: number, modeIndex: number) {
  curTab.value = tabIndex
  mode.value = modeIndex
  timeTab.value = 0
  roomDayControl?.destroyChart()
  if (curTab.value === 0) {
    let findIndex = degrees.value.findIndex((degree) => degree.value === Number(setTemp.value))
    curIndex.value = findIndex
    tempIndex.value = findIndex
  } else if (curTab.value === 1) {
    getRoomDayData(1, 36)
  } else {
    getRoomDayData(1, 20)
  }
}
/**
 * 切换快速模式tab
 */
function chooseManual(modeIndex: number, temp: number) {
  if (mode.value === modeIndex || pickState.value) return
  mode.value = modeIndex
  if (modeIndex === tempMode.value) temp = Number(setTemp.value)
  let mateIndex = degrees.value.findIndex((item) => item.value === temp)
  curIndex.value = mateIndex
  tempIndex.value = mateIndex
}
/**
 * 选择温度
 * @param index
 */
function chooseTemp(index: number) {
  curIndex.value = index
  tempIndex.value = index
}
/**
 * 滚动
 * @param state
 */
function changePickState(state: boolean) {
  pickState.value = state
}
/**
 * 确定
 */
const applayAllRoomVisible = ref(false)
const optionConfirm = actionDebounce({
  call: async () => {
    if (roomKey.value == 'Rm0' && roomList.value.length > 1) {
      applayAllRoomVisible.value = true
    } else {
      optionConfirmManual(false, 0)
    }
  },
})
/**
 * 取消应用所有房间
 */
function cancelmManual() {
  showRoomDialog.value = false
  optionConfirmManual(false, 0)
}
/**
 * 确定应用所有房间
 */
function confirmManual() {
  showRoomDialog.value = false
  optionConfirmManual(true, 0)
}
/**
 * 区分模式下发命令
 */
const optionConfirmManual = actionDebounce({
  call: async (allroom: boolean, count: number) => {
    if (curTab.value === 0) {
      setManual(allroom, 0)
    } else {
      let data = roomDayControl?.lineData.value ? roomDayControl?.lineData.value : [{ value: [0, 0] }]
      let newRoomConfig = setTTProgramMode(roomConfig.value, 0) + ''
      newRoomConfig =
        setTTProgramMode(newRoomConfig, curTab.value === 1 ? parseInt('0x24', 16) : parseInt('0x14', 16)) + ''
      let params: SettingsSubmitType = {
        settings: [],
      }
      if (!allroom) {
        if (isMR100IRF.value) {
          params = {
            settings: [
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1',
                value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2',
                value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3',
                value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4',
                value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
                value: setTTProgramDay(roomState.value + '', timeTab.value === 0 ? 1 : 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
                value: newRoomConfig,
              },
            ],
          }
        } else {
          params = {
            settings: [
              {
                key: 'BSH.Common.Setting.TlBl',
                value: 0,
              },
              {
                key: 'BSH.Common.Setting.TlRm',
                value: 0,
              },
              {
                key: 'BSH.Common.Setting.' + roomKey.value + 'Mode',
                value: 0,
              },
              {
                key: 'BSH.Common.Setting.' + roomKey.value + 'TmMode',
                value: curTab.value === 1 ? parseInt('0x24', 16) : parseInt('0x14', 16),
              },
              {
                key: 'BSH.Common.Setting.' + roomKey.value + 'TmDay',
                value: timeTab.value === 0 ? 1 : 2,
              },
              {
                key: 'BSH.Common.Setting.' + roomKey.value + 'TmDx1',
                value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
              },
              {
                key: 'BSH.Common.Setting.' + roomKey.value + 'TmDx2',
                value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
              },
              {
                key: 'BSH.Common.Setting.' + roomKey.value + 'TmDx3',
                value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
              },
              {
                key: 'BSH.Common.Setting.' + roomKey.value + 'TmDx4',
                value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
              },
            ],
          }
        }
      } else {
        if (isMR100IRF.value) {
          params = {
            settings: [],
          }
        } else {
          params = {
            settings: [
              {
                key: 'BSH.Common.Setting.TlBl',
                value: 0,
              },
              {
                key: 'BSH.Common.Setting.TlRm',
                value: 0,
              },
            ],
          }
        }
        let max = roomList.value.length
        if (max > PACKAGE_ARRAY[count + 1]) {
          max = PACKAGE_ARRAY[count + 1]
        }
        for (let i = PACKAGE_ARRAY[count]; i < max; i++) {
          if (isMR100IRF.value) {
            params.settings.push(
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx1',
                value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx2',
                value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx3',
                value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx4',
                value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'State',
                value: setTTProgramDay(roomState.value + '', timeTab.value === 0 ? 1 : 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Config',
                value: newRoomConfig,
              }
            )
          } else {
            params.settings.push(
              {
                key: 'BSH.Common.Setting.' + roomList.value[i].key + 'Mode',
                value: 0,
              },
              {
                key: 'BSH.Common.Setting.' + roomList.value[i].key + 'TmMode',
                value: curTab.value === 1 ? parseInt('0x24', 16) : parseInt('0x14', 16),
              },
              {
                key: 'BSH.Common.Setting.' + roomList.value[i].key + 'TmDay',
                value: timeTab.value === 0 ? 1 : 2,
              },
              {
                key: 'BSH.Common.Setting.' + roomList.value[i].key + 'TmDx1',
                value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
              },
              {
                key: 'BSH.Common.Setting.' + roomList.value[i].key + 'TmDx2',
                value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
              },
              {
                key: 'BSH.Common.Setting.' + roomList.value[i].key + 'TmDx3',
                value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
              },
              {
                key: 'BSH.Common.Setting.' + roomList.value[i].key + 'TmDx4',
                value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
              }
            )
          }
        }
      }

      const res = await setTTSetting(haId.value, params)
      if (res.code === 0) {
        if (allroom && PACKAGE_ARRAY[count + 1] < roomList.value.length) {
          optionConfirmManual(allroom, count + 1)
        } else {
          uni.showToast({
            title: '设置成功',
            icon: 'none',
          })
        }
      }
    }
  },
})
/**
 * 格式化tmdx数据,先将每个转成十六进制合并，再转十进制
 */
function formatTmDx(hour: number, miu: number, temp: number) {
  let concatData = 0
  if (isMR100IRF.value) {
    let hourminute = hour * 10 + miu
    let concatText = fixNum0(hourminute.toString(16)) + fixNum0(temp.toString(16))
    concatData = parseInt(concatText, 16)
  } else {
    let concatText = fixNum0(temp.toString(16)) + fixNum0(miu.toString(16)) + fixNum0(hour.toString(16))
    concatData = parseInt(concatText, 16)
  }
  return concatData
}
// 补0
function fixNum0(num: string) {
  return num.length < 2 ? '0' + num : num
}
/**
 * 快速模式设置
 */
async function setManual(allroom: boolean, count: number) {
  let params: SettingsSubmitType = {
    settings: [],
  }
  if (!allroom) {
    if (isMR100IRF.value) {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set',
            value: degrees.value[tempIndex.value].value * 10,
          },
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
            value: setTTRoomMode(roomConfig.value, mode.value + ''),
          },
        ],
      }
    } else {
      params.settings.push(
        {
          key: 'BSH.Common.Setting.TlBl',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.TlRm',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.' + roomKey.value + 'Mode',
          value: mode.value,
        },
        {
          key: 'BSH.Common.Setting.' + roomKey.value + 'TmMode',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.' + roomKey.value + 'Set',
          value: degrees.value[tempIndex.value].value * 10,
        }
      )
    }
  } else {
    // 应用到所有房间

    let max = roomList.value.length
    if (max > PACKAGE_ARRAY[count + 1]) {
      max = PACKAGE_ARRAY[count + 1]
    }
    for (let i = PACKAGE_ARRAY[count]; i < max; i++) {
      if (isMR100IRF.value) {
        params.settings.push(
          {
            key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Set',
            value: degrees.value[tempIndex.value].value * 10,
          },
          {
            key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Config',
            value: setTTRoomMode(roomConfig.value, mode.value + ''),
          }
        )
      } else {
        params.settings.push(
          {
            key: 'BSH.Common.Setting.TlBl',
            value: 0,
          },
          {
            key: 'BSH.Common.Setting.TlRm',
            value: 0,
          },
          {
            key: 'BSH.Common.Setting.' + roomList.value[i].key + 'Mode',
            value: mode.value,
          },
          {
            key: 'BSH.Common.Setting.' + roomList.value[i].key + 'TmMode',
            value: 0,
          },
          {
            key: 'BSH.Common.Setting.' + roomList.value[i].key + 'Set',
            value: degrees.value[tempIndex.value].value * 10,
          }
        )
      }
    }
  }
  await setSetting(params, allroom, 0)
}
/**
 * 下发设置指令
 * @param params
 */
async function setSetting(params: {}, allroom?: boolean, count?: number) {
  const res = await setTTSetting(haId.value, params)
  if (res.code === 0) {
    if (allroom && count && PACKAGE_ARRAY[count + 1] < roomList.value.length) {
      setManual(allroom, count + 1)
    } else {
      uni.showToast({
        title: '设置成功',
        icon: 'none',
      })
    }
  }
}
/**
 * 点击开关机
 */
const onOffVisible = ref(false)
const setOff = actionDebounce({
  call: async () => {
    if (powerStatus.value) {
      onOffVisible.value = true
    } else {
      onOff()
    }
  },
})
/**
 * 下发开关机指令
 */
function onOff() {
  let params = {}
  if (isMR100IRF.value) {
    params = {
      settings: [
        {
          key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
          value: setTTRoomMode(roomConfig.value, powerStatus.value ? '5' : '2'),
        },
      ],
    }
  } else {
    params = {
      settings: [
        {
          key: 'BSH.Common.Setting.TlBl',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.TlRm',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.' + roomKey.value + 'Mode',
          value: powerStatus.value ? '5' : '2',
        },
      ],
    }
  }
  showLoading(async () => {
    await setSetting(params)
  })
}

/**
 * 显示机器学习描述
 */
function showPreheatDesc() {
  preheatDesc.value = true
}
/**
 * 控制机器自学习
 */
const controlPreheat = actionDebounce({
  call: async () => {
    let params = {}
    if (isMR100IRF.value) {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
            value: setRoomPreheat(roomState.value + '', preHeat.value ? '0' : '1'),
          },
        ],
      }
    } else {
      params = {
        settings: [
          {
            key: 'BSH.Common.Setting.TlBl',
            value: 0,
          },
          {
            key: 'BSH.Common.Setting.TlRm',
            value: 0,
          },
          {
            key: 'BSH.Common.Setting.' + roomKey.value + 'Preheat',
            value: preHeat.value ? 0 : 1,
          },
        ],
      }
    }
    showLoading(async () => {
      await setSetting(params)
    })
  },
})
/**
 * 切换周六周日
 */
function switchTimeTab(curTimeIdx: number) {
  if (curTimeIdx === timeTab.value) return
  timeTab.value = curTimeIdx
  roomDayControl?.destroyChart()
  if (curTimeIdx === 0) {
    getRoomDayData(1, 36)
  } else {
    getRoomDayData(2, 36)
  }
}

/**
 * 获取房间编程数据
 */
function getRoomDayData(day: number, tmMode: number) {
  showLoading(async () => {
    let postData = {}
    if (isMR100IRF.value) {
      postData = {
        data: {
          data: [
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
              value: setTTProgramDay(roomState.value + '', day),
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
              value: setTTProgramMode(roomConfig.value, tmMode),
            },
          ],
        },
      }
    } else {
      postData = {
        data: {
          room: roomId.value,
          day,
          tmMode,
        },
      }
    }
    let sourceData = []
    tempLineData.value = []
    if (isMR100IRF.value) {
      const res = await getBLTTSpecialSetting(haId.value, postData)
      if (res.code === 0) {
        const { blSettings } = res.data
        let sourceDict: Record<string, BLTTSettingValueType> = {}
        for (let i = 0; i < blSettings.length; i++) {
          if (blSettings[i].key.indexOf('SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx') != -1) {
            let key = blSettings[i].key.replace('SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx', '')
            sourceDict[key.toString()] = blSettings[i]
          }
        }
        let formatDict = Object.keys(sourceDict).sort()
        for (var key in formatDict) {
          sourceData.push(sourceDict[formatDict[key]])
        }
        sourceData.forEach((e) => {
          let curData = Number(e.value).toString(16)
          while (curData.length < 5) {
            curData = 0 + curData
          }
          let temp = parseInt(curData.substring(3, 5), 16) / 2
          let hourminute = parseInt(curData.substring(0, 3), 16)
          let hour = (hourminute - (hourminute % 10)) / 10
          tempLineData.value.push([hour, temp])
        })
      }
    } else {
      const resTT = await getBLTTSetting(haId.value, postData)
      if (resTT.code === 0) {
        sourceData = resTT.data.value
        sourceData.forEach((e) => {
          let curData = Number(e.value).toString(16)
          while (curData.length < 6) {
            curData = 0 + curData
          }
          let temp = parseInt(curData.substring(0, 2), 16) / 2
          let hour = parseInt(curData.substring(4, curData.length), 16)
          tempLineData.value.push([hour, temp])
        })
      }
    }
    dataV.value = [
      {
        value: [-5, 0],
      },
    ]
    for (let i = 0; i < tempLineData.value.length; i++) {
      let value = {
        value: [tempLineData.value[i][0], 0],
      }
      dataV.value.push(value)
    }
    dataV.value.push({
      value: [30, 0],
    })
    roomDayControl?.initData()
    initChart()
    uni.hideLoading()
  })
}
/**
 * 打开快速加热弹框
 */
function showQuickWarmUpPopView() {
  if (rapidHeat.value) {
    closeRapidHeat()
  } else {
    showRapidHeat.value = true
  }
}
/**
 * 关闭快速加热模式
 */
async function closeRapidHeat() {
  let params = {}
  if (isMR100IRF.value) {
    params = {
      settings: [
        {
          key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost',
          value: 0,
        },
      ],
    }
  } else {
    params = {
      settings: [
        {
          key: 'BSH.Common.Setting.TlBl',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.TlRm',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.' + roomKey.value + 'Boost',
          value: 0,
        },
      ],
    }
  }
  await setSetting(params)
  rapidHeat.value = false
}
/**
 * 修改快速加热温度
 * @param value
 */
function changHeatTemp(value: number) {
  curHeatTemp.value = value
}
/**
 * 修改快速加热时间
 */
function changeRapidHeat(value: number) {
  curHeatTime.value = value
}
/**
 * 确定快速加热发送命令
 */
const confirmRapidHeat = actionDebounce({
  call: async () => {
    let rapidHeatData = '0x' + (curHeatTemp.value - 24) + curHeatTime.value
    let params = {}

    if (isMR100IRF.value) {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost',
            value: parseInt(rapidHeatData, 16),
          },
        ],
      }
    } else {
      params = {
        settings: [
          {
            key: 'BSH.Common.Setting.TlBl',
            value: 0,
          },
          {
            key: 'BSH.Common.Setting.TlRm',
            value: 0,
          },
          {
            key: 'BSH.Common.Setting.' + roomKey.value + 'Boost',
            value: parseInt(rapidHeatData, 16),
          },
        ],
      }
    }
    await setSetting(params)
    rapidHeat.value = true
    showRapidHeat.value = false
  },
})

const messages = ref<WS.MessageItem[]>([])
let tmdxChangeSocketTimestamp = 0
/**
 * 监听
 */
const observeSettingKeys = computed(() => [
  'BSH.Common.Setting.Rm' + roomId.value + 'Set',
  'BSH.Common.Setting.Rm' + roomId.value + 'Mode',
  'BSH.Common.Setting.Rm' + roomId.value + 'Temp',
  'BSH.Common.Setting.Rm' + roomId.value + 'Preheat',
  'BSH.Common.Setting.Rm' + roomId.value + 'Boost',
  'BSH.Common.Setting.Rm' + roomId.value + 'TmMode',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Temp',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4',
  TT_SUMMER_MODE,
  TT_STATUS_MCUSTATUS,
  TT_SETTING_BlState,
])
const observes: Remote.BatchObserve<TTController.Store>[] = [
  {
    matcher: (msg) => observeSettingKeys.value.includes(msg.key),
    handler: (msg, remote, msgContext) => handleMsg(msg, msgContext?.timestamp || 0),
  },
]
function listenMessages() {
  control.value?.remote.addBatchObserves(observes)
}
/**
 * 监听信息
 * @param item
 * @returns
 */
function handleMsg(item: WS.MessageItem, timestamp: number) {
  console.error('handleMsg', item)
  if (!item) {
    return
  }
  switch (item.key) {
    case 'BSH.Common.Setting.Rm' + roomId.value + 'Set':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set':
      let newIndex = degrees.value.findIndex((degree: { value: number }) => degree.value === Number(item.value) / 10)
      curIndex.value = newIndex
      tempIndex.value = newIndex
      setTemp.value = Number(item.value) + ''
      break
    case 'BSH.Common.Setting.Rm' + roomId.value + 'Mode':
      mode.value = Number(item.value)
      tempMode.value = Number(item.value)
      modeText.value = MODES.get(Number(item.value)) || '自动'
      powerStatus.value = !(Number(item.value) === 5)
      break
    case 'BSH.Common.Setting.Rm' + roomId.value + 'Temp':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Temp':
      curTemp.value = Number(item.value) / 10 + ''
      break
    case 'BSH.Common.Setting.Rm' + roomId.value + 'Preheat':
      preHeat.value = item.value === 1
      break
    case 'BSH.Common.Setting.Rm' + roomId.value + 'Boost':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost':
      let formatBoost = Number(item.value).toString(16)
      let isbool = !(Number(item.value) === 0)
      rapidHeat.value = isbool
      if (isbool) {
        curHeatTemp.value = 24 + Number(formatBoost.substr(0, 1))
        curHeatTime.value = Number(formatBoost.substr(1, 1))
        candidateTemp.value = 24 + Number(formatBoost.substr(0, 1))
        candidateTime.value = Number(formatBoost.substr(1, 1))
      }
      break
    case 'BSH.Common.Setting.Rm' + roomId.value + 'TmMode':
      curTab.value = item.value === 20 ? 2 : item.value === 0 ? 0 : 1
      if (curTab.value !== 0) {
        getRoomDayData(1, Number(item.value))
      }
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config':
      roomConfig.value = item.value as string
      let newMode = getTTRoomMode(item.value as string)
      let tmMode = getTTRoomTmMode(item.value as string)
      let newCurTab = 0
      if (newMode === 0) {
        if (tmMode === 0) {
          newCurTab = 2
        } else if (tmMode === 1) {
          newCurTab = 1
        }
      } else {
        newCurTab = 0
      }
      mode.value = newMode
      tempMode.value = newMode
      modeText.value = MODES.get(newMode) || '自动'
      powerStatus.value = !(newMode === 5)
      curTab.value = newCurTab
      if (newMode === 0) {
        if (Math.abs(tmdxChangeSocketTimestamp - timestamp) > 1000) {
          tmdxChangeSocketTimestamp = timestamp
          if (curTab.value === 1) {
            if (timeTab.value === 0) {
              getRoomDayData(1, 36)
            } else {
              getRoomDayData(2, 36)
            }
          } else if (curTab.value === 2) {
            getRoomDayData(1, 20)
          }
        }
      }
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State':
      roomState.value = item.value as number
      let newPreHeat = getRoomPreheat(item.value as string)
      preHeat.value = newPreHeat ? true : false
      break
    case TT_STATUS_MCUSTATUS:
      mcuStatus.value = item.value as number
      break
    case TT_SETTING_BlState:
      if (getTTSummerMode(item.value as string) === 1) {
        summerMode.value = true
      } else {
        summerMode.value = false
      }
      if (getTTAutoMode(item.value as string) === 1) {
        manualMode.value = true
      } else {
        manualMode.value = false
      }
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4':
      //设备端切换编程模式，将直接变成家有老幼模式。所以只需要再该模式下处理编程数据的变化
      if (Math.abs(tmdxChangeSocketTimestamp - timestamp) > 1000) {
        tmdxChangeSocketTimestamp = timestamp
        if (curTab.value === 1) {
          if (timeTab.value == 0) {
            getRoomDayData(1, 36)
          } else {
            getRoomDayData(2, 36)
          }
        } else if (curTab.value === 2) {
          getRoomDayData(1, 20)
        }
      }
      break
    case TT_SUMMER_MODE:
      let newSummerMode = Number(item.value) === 1
      if (newSummerMode) {
        onBack()
      }
      break
    default:
      break
  }
}
/**
 * 返回上一页
 */
function onBack() {
  uni.navigateBack()
}

/**
 * 初始化图表
 */
const instance = getCurrentInstance()
const envStore = useEnvStore()
let ecComponent: EcCanvasComponent | null = null
// 点击按钮后初始化图表
function initChart() {
  ecComponent = (instance as any).ctx.selectComponent('#myChartDomLine') as EcCanvasComponent | null
  if (!ecComponent) {
    return uni.hideLoading()
  }

  ecComponent.init((canvas, width, height) => {
    /*
     * 获取组件的 canvas、width、height 后的回调函数
     * 在这里初始化图表
     */
    const chart = echarts.init(canvas, void 0, {
      width,
      height,
      devicePixelRatio: envStore.systemInfo.pixelRatio,
    })
    roomDayControl?.setChartInstance(chart)
    roomDayControl?.setOption()
    // wx.hideLoading()

    // 注意这里一定要返回 chart 实例，否则会影响事件处理等
    return chart
  })
}
</script>

<style scoped lang="less">
@import '@/styles/common.less';
@import '@/styles/switch.less';
@import '../style//room.less';

.switch-icon {
  width: 90rpx;
  height: 60rpx;
}
</style>
